package com.jun.common.redis.properties;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author yuejun.li
 * @date 2024/7/25 17:35:44
 */
@ConfigurationProperties(prefix = "spring.redis")
public class RedisTemplateProperties {

    public static final String FAST_JSON = "fastJson";
    public static final String JACK_JSON = "jackson";

    private String serialization = JACK_JSON;

    public String getSerialization() {
        return serialization;
    }

    public void setSerialization(String serialization) {
        this.serialization = serialization;
    }

    //=================================redisTemplate序列化==================================
    public void serialization(RedisTemplate<String, Object> redisTemplate) {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        switch (this.getSerialization()) {
            case JACK_JSON :
                Jackson2JsonRedisSerializer<Object> jackson2Serializer = new Jackson2JsonRedisSerializer<>(Object.class);
                // ObjectMapper是Jackson提供的一个类，作用是将java对象与json格式相互转化
                ObjectMapper om = new ObjectMapper();
                om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
                // 所有非final类型
                om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
                jackson2Serializer.setObjectMapper(om);
                // 设置序列化器
                redisTemplate.setKeySerializer(stringRedisSerializer);
                redisTemplate.setValueSerializer(jackson2Serializer);
                redisTemplate.setHashKeySerializer(stringRedisSerializer);
                redisTemplate.setHashValueSerializer(jackson2Serializer);
                break;
            case FAST_JSON :
                FastJsonRedisSerializer<?> serializer = new FastJsonRedisSerializer<>(Object.class);
                // key的序列化采用StringRedisSerializer
                redisTemplate.setKeySerializer(stringRedisSerializer);
                redisTemplate.setHashKeySerializer(stringRedisSerializer);
                // value值的序列化采用fastJsonRedisSerializer
                redisTemplate.setValueSerializer(serializer);
                redisTemplate.setHashValueSerializer(serializer);
                break;
            default: break;
        }
        // 可以没有 但最好加上
        redisTemplate.afterPropertiesSet();
    }
}
